package rm;

import core.Config;
import java.io.File;
import java.io.IOException;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class ProcLauncher {

	public static boolean launchProcess(Node node, RMProcess procDesc)
			throws IOException, InterruptedException {

		Connection conn = new Connection(node.getHostName());
		conn.connect();
		boolean isAuth = conn.authenticateWithPublicKey(node.getUser(),
				new File(Config.SSH_DSA), null);

		if (!isAuth) {
			throw new IOException("Authentication failed");
		}
		System.out.println("Launcher =>");
		System.out.println("\t Lancando em: " + node.getHostName());
		System.out.println("\t\t" + procDesc.toString() + "\n");
		Session sess = conn.openSession();
		conn.setTCPNoDelay(true);
		sess.execCommand(Config.NOHUP_BIN + procDesc + " >" + Config.LOG_DIR
				+ "Saida_" + node.getId() + ".out 2>" + Config.LOG_DIR
				+ "SaidaErro_" + node.getId() + ".out &");
		sess.waitForCondition(ChannelCondition.STDOUT_DATA, 0);
		return true;
	}
}
